package com.gzy.rpsm.property.controller;

import com.gzy.rpsm.property.pojo.PageResult;
import com.gzy.rpsm.property.pojo.ResponsePojo;
import com.gzy.rpsm.property.pojo.UnpaidOwner;
import com.gzy.rpsm.property.pojo.User;
import com.gzy.rpsm.property.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.MediaType;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Optional;

@RestController
@RequestMapping("/user")
@Api(tags = "业主相关 api")
public class UserController {
    @Autowired
    private UserService userService;

    @ApiOperation(value = "根据账号和密码进行登录操作，只需账号和密码。回个人信息和 token 字符串",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account", type = "String", required = true),
            @ApiImplicitParam(name = "password", type = "String", required = true)
    })
    @PostMapping("/login")
    public ResponsePojo<User> login(@RequestParam("account") String account, @RequestParam("password") String password) {
        User result = userService.login(account, password);
        if (Optional.ofNullable(result).isPresent()) {
            return ResponsePojo.success(result);
        } else {
            return ResponsePojo.fail(null, "验证失败");
        }
    }

    @PostMapping("/insert")
    @ApiOperation(value = "新增业主信息， 默认为未激活的状态， 采用默认密码,生成随机账号。 roomid 通过级联菜单获得",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "idcard", type =
                    "String", required = true),
            @ApiImplicitParam(name = "age", type = "Integer", required
                    = true),
            @ApiImplicitParam(name = "gender", type =
                    "Integer", required = true),
            @ApiImplicitParam(name = "username", type =
                    "String", required = true),
            @ApiImplicitParam(name = "user_roomid", type =
                    "Integer", required = true),
    })
    public ResponsePojo<Integer> insertUser(@ApiIgnore User user) {
        //需验证 roomid 是否存在。 目前省略掉该步骤， 可以拓展完成
        user.setPassword("123456");
        // 根据用户名的 MD5 值和时间戳生成用户账号。 可能有极小概率重复。
        String name = DigestUtils.md5DigestAsHex(user.getUsername().getBytes(StandardCharsets.UTF_8)).substring(13, 20);
        name = name.concat(System.currentTimeMillis() % 10000 + "");
        user.setAccount(name);
        user.setUser_type((short) 3);//设置为业主类型
        user.setUser_status((short) 33);//设置为未激活状态
        Integer result = null;
        try {
            result = userService.insertUser(user);
            return ResponsePojo.success(result);
        } catch (DuplicateKeyException e) {
            e.printStackTrace();
            return ResponsePojo.fail(result, "身份证重复");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponsePojo.fail(result, "未知异常，请联系管理员");
        }
    }

    @GetMapping("/pageOfOwners")
    @ApiOperation(value = "分页的业主信息。 默认为第一页， 每页默认 10 条数据。 ",
            notes = "若当前页小于 1， 强制为 1； 若每页行数小于 1， 强制为 1")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", defaultValue = "1"),
            @ApiImplicitParam(name = "size", defaultValue = "10")
    })
    public ResponsePojo<PageResult<User>> pageOfOwners(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        PageResult<User> page = userService.pageOfOwner(current, size);
        return ResponsePojo.success(page);
    }

    @PutMapping("/updateStatus/{userid}")
    @ApiOperation( value="修改用户状态， 主要是更换业主后",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name="userid",type =
                    "Integer",required = true,paramType = "path"),
            @ApiImplicitParam(name="user_status",type =
                    "Integer",required = true,paramType = "query"),
    })
    public ResponsePojo<Integer> changeUserStatus(@ApiIgnore User user){
        int result = userService.changeUserStatus(user);
        if(result == 0){
            return ResponsePojo.fail(result,"该用户 id 失效");
        }
        return ResponsePojo.success(result);
    }

    @GetMapping("/id/{userid}")
    @ApiOperation( value="根据用户 id 查询用户详细信息")
    public ResponsePojo<User> queryById(@PathVariable("userid") Integer id){
        User u = userService.queryById(id);
        //int a =1/0;
        if(Optional.ofNullable(u).isPresent()){
            return ResponsePojo.success(u) ;
        }
        return ResponsePojo.fail(u,"该 id 不存在对应用户");
    }
    @GetMapping("/me")
    @ApiOperation( value="获取当前登录用户信息")
    public ResponsePojo<User> me(HttpServletRequest request){
        Integer userId = (Integer) request.getAttribute("userId");
        User u = userService.queryById(userId);
        return ResponsePojo.success(u) ;
    }

    @GetMapping("/unpaidOwnerList")
    @ApiOperation(value = "单项费用的欠费名单查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", defaultValue = "1"),
            @ApiImplicitParam(name = "size", defaultValue = "10"),
            @ApiImplicitParam(name = "typeId", required = true)
    })
    public ResponsePojo<PageResult<UnpaidOwner>> unpaidOwnerList(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            Integer typeId) {
        return ResponsePojo.success(userService.pageOfUnpaidOwnerList(current, size, typeId));
    }
}